import Vue from "vue";
import Vuex from "vuex";
import { getParamString } from "@/utils/paramsFitter";
import { getMusicLyricInfo } from "../../Api/seachApi";

//将字符串xx:xx的时间格式处理成秒
function _timeForm(time) {
  let index = time.indexOf(":");
  let min = time.substring(0, index);
  let seconds = time.substring(index + 1, time.length);
  return min * 60 + seconds * 1;
}
const state = {
  // audio
  audioElement: null,
  audioSrc: "",
  currentTime: 0, //当前播放时长
  tagetTime: 0, //播放总时长
  musicID: "", //音乐的ID值
  musicListID: getParamString(localStorage.getItem("musicListID")), //歌单的ID值

  isClickPlay: false, // 是否点击播放
  isShowLyric: true, // 是否显示歌词

  isCheakInfomate: false, // 是否查看歌单详情列表

  oneMusicPlayData: [], //   单首歌曲列表详情

  lyricData: [], //歌词数据

  musicPlayListData: [], // 歌曲播放列表数据

  bgcImg: "", //设置背景图片

  // isShowPlaylist: false, // 是否显示歌单页面
  isRankingList: false, // 是否显示榜单页面
  isMusicPlayList: false, //是否显示播放列表页面

  // 歌曲播放顺序
  LoopPlayOrder: getParamString(localStorage.getItem("LoopPlayOrder")), //""(空)默认：循环播放，"0":循环播放，"1":单曲循环播放，"2"：随机播放
};
//去除字符串中的括号（转化函数）
function getClassName(param) {
  var modalityArrClassName = "";
  if (param.match(/[\(\)\[\]\{\}]/g)) {
    modalityArrClassName = param.replace("[", "").replace("]", ";");
  } else {
    modalityArrClassName = param;
  }
  return modalityArrClassName;
}

const mutations = {
  //歌词数据
  lyricData(state, data) {
    //   console.log('lyricData歌词数据',data);
    // let lyrArr = [];
    // let arr = data.split(/\n/);
    // arr.map((v) => {
    //   let lcleft = getClassName(v);
    //   let lcleftTime = lcleft.split(";");
    //   // console.log("lcleftTime",lcleftTime)
    //   let times = lcleftTime[0].substr(1).split(":");
    //   //  console.log("times",times)
    //   if (times[0] !== '') {
    //     lyrArr.push({
    //       time: Number(times[0] * 60) + Number(times[1]),
    //       text: lcleftTime[1],
    //       bool: false,
    //     });
    //   }
    // });
    // state.lyricData = lyrArr; //JSON.parse(JSON.stringify(lyrArr));
    // console.log("state.lyricData =", state.lyricData);
    // state.lyricData = data;
    // let

    let str = data;
    let lyrs = [];
    //  //获取歌词贡献者
    //  let regUser = /\[(.*)\]\n/gim;

    //  let user = regUser.exec(str);
    //  str = str.substring(user[0].length, str.length);

    //匹配歌词
    let reg = /\[(.*)\](.*)\n/gim;
    let res;
    while ((res = reg.exec(str))) {
      lyrs.push({ time: _timeForm(res[1]), lyr: res[2] });
    }
    state.lyricData = JSON.parse(JSON.stringify(lyrs));
  },

  // 歌曲播放列表数据
  SetMusicPlayListData(state, value) {
    if (value === "") {
      return;
    }
    state.musicPlayListData.forEach((el) => {
      // console.log("ashkjdahjhgaskj",el == musicPlayListData);
      if (el == value) {
        return;
      }
    });
    // let DataPlay = []
    // console.log(typeof musicPlayListData);
    // 批量添加
    if (Array.isArray(value)) {
      state.musicPlayListData = value;
    } else {
      state.musicPlayListData.unshift(value);
    }
    // console.log("歌曲播放列表数据", state.musicPlayListData);
    state.musicPlayListData = [...new Set(state.musicPlayListData)];
  },
  //显示播放列表页面

  isMusicPlayList(state, bool) {
    state.isMusicPlayList = bool;
  },
  //   歌曲列表详情
  OneMusicPlayData(state, oneMusicPlayData) {
    state.oneMusicPlayData = oneMusicPlayData;
  },
  // 歌曲ID
  SetMusicID(state, musicId) {
    state.musicID = musicId;
  },
  // 歌单ID
  musicListID(state, data) {
    state.musicListID = data;
    localStorage.setItem("musicListID", data);
  },
  audioSrc(state, audioSrc) {
    state.audioSrc = audioSrc;
  },
  // 使用对象传值

  initAudio(state, audio) {
    state.audioElement = audio;
  },
  getCurrentTime(state, time) {
    state.currentTime = time;
  },
  getTagetTime(state, time) {
    state.tagetTime = time;
  },

  // 是否查看详情列表
  isCheakInfomate(state, isCheakInfomate) {
    state.isCheakInfomate = isCheakInfomate;
  },
  // 是否显示榜单页面
  isRankingList(state, isRankingList) {
    state.isRankingList = isRankingList;
  },
  // 是否显示歌单页面
  // isShowPlaylist(state, isShowPlaylist) {
  //   // console.log(isClickPlay)
  //   state.isShowPlaylist = isShowPlaylist;
  // },

  // 是否点击播放
  isClickPlay(state, bool) {
    state.isClickPlay = bool;
  },
  // 是否显示歌词
  isShowLyric(state, isShow) {
    // console.log(isClickPlay)
    state.isShowLyric = isShow;
  },
  // 设置背景图片
  bgcImg(state, bgcImg) {
    state.bgcImg = bgcImg;
  },
  // 设置曲播放顺序
  Commit_LoopPlayOrder(state, value) {
    state.LoopPlayOrder = value;
    localStorage.setItem("LoopPlayOrder", value);
  },
};
const actions = {
  GET_MUSIC_LYRIC({ commit }) {
    getMusicLyricInfo({ id: state.musicID })
      .then((res) => {
        commit("lyricData", res.lrc.lyric);
      })
      .catch((err) => {
        // console.log(err);
      });
  },
  // 下一首歌曲
  Get_Next_Player({ commit }, musicID) {
    let index = state.musicPlayListData.findIndex((item) => item === musicID);
    if (index >= state.musicPlayListData.length - 1) {
      commit("SetMusicID", state.musicPlayListData[0]);
    } else {
      commit("SetMusicID", state.musicPlayListData[index + 1]);
    }
  },
  // 上一首歌曲
  Get_Prev_Player({ commit }, musicID) {
    let index = state.musicPlayListData.findIndex((item) => item === musicID);
    if (index - 1 <= -1) {
      commit(
        "SetMusicID",
        state.musicPlayListData[state.musicPlayListData.length - 1]
      );
    } else {
      commit("SetMusicID", state.musicPlayListData[index - 1]);
    }
  },
  // 设置曲播放顺序
  Set_LoopPlayOrder({ commit }, value) {
    commit("Commit_LoopPlayOrder", value);
  },
  // 随机播放功能
  Set_RandomPlay({ commit }) {
    // 设置随机下标
    let randomIndex =Math.round( Math.random() * (state.musicPlayListData.length - 1));
    // console.log("设置随机下标", randomIndex);
    commit("SetMusicID", state.musicPlayListData[randomIndex]);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
